package com.cheyun.netsalev3


import android.content.Intent
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import android.widget.PopupWindow
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.cheyun.netsalev3.adapter.BadgeTabLayoutAdapter
import com.cheyun.netsalev3.databinding.DmClueTypePopItemBinding
import com.cheyun.netsalev3.databinding.FragmentDmZhtBinding
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.view.dm.DmSearchActivity
import com.cheyun.netsalev3.view.dm.DmZhtListFragment
import com.cheyun.netsalev3.viewmodel.DmZhtViewModel
import com.cheyun.netsalev3.widget.TabBadgeView
import com.google.android.material.tabs.TabLayout
import com.jeremyliao.liveeventbus.LiveEventBus


class DmZhtFragment : BaseFragment<FragmentDmZhtBinding>() {
    override fun initContentView(): Int {
        return R.layout.fragment_dm_zht
    }
    var popupWindow: PopupWindow? = null
    private var listFragmet = ArrayList<Fragment>()

    var titles = arrayListOf("全部", "待处理", "有效","无效", "待分配")
    var status = arrayListOf(1, 2, 3, 4,5)
    var badges = arrayListOf(0,0,0,0,0)
    var mBadgeViews: ArrayList<TabBadgeView>? = null
    lateinit var pagerAdapter:BadgeTabLayoutAdapter;
    init {
        var data = MySharedPreferences.getDmLoginData()
        if(data?.clue_mgr == 0){
            titles = arrayListOf("全部", "待处理", "有效","无效")
            badges = arrayListOf(0,0,0,0)
            status = arrayListOf(1,2,3,4)
        }
    }

    private var planType: Int = 2
    private var dealed:Int = -1

    override fun initViewModel(): ViewModel? {
        activity?.apply {
            val factory = InjectorUtils.getDmZhtViewModelFactory(planType,dealed,"",status)
            return ViewModelProviders.of(this, factory).get(DmZhtViewModel::class.java)
        }
        return null
    }

    override fun initData() {

    }

    override fun lazyInit() {
        Log.i(TAG,"override lazyinit")
    }

    override fun initView() {
        for (i in titles.indices) {
            listFragmet.add(DmZhtListFragment.newInstance(planType,dealed, status[i]))
        }
        pagerAdapter = BadgeTabLayoutAdapter(childFragmentManager, listFragmet,this.context!!)
        pagerAdapter.titles = titles
        binding.viewPager.offscreenPageLimit = 5
        binding.viewPager.adapter = pagerAdapter
        binding.tabLayout.setupWithViewPager(binding.viewPager)

        binding.rightImg?.setOnClickListener {
            var intent = Intent(this.activity, DmSearchActivity::class.java)
            startActivity(intent)
        }
        binding.searchBut.setOnClickListener {
            showPop(it)
        }
        initBadgeViews()
        setUpTabBadge()

        //选中的位置
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(p0: TabLayout.Tab?) {

            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                var pos = binding.tabLayout.selectedTabPosition

                var nke = status[pos]
                binding.viewModel?.totlelist!![nke]?.observe(this@DmZhtFragment, Observer {
                    binding.totleText.text = titles[pos] + it.toString() + "人"
                    showTips()
                })
            }
        })

        if(status.size>0 && titles.size>0) {
            var nke = status[0]
            binding.viewModel?.totlelist!![nke]?.observe(this, Observer {
                binding.totleText.text = titles[0] + it.toString() + "人"
                showTips()
            })
        }
//        var showBack = this.activity?.intent?.hasExtra("showMy");
//        if(showBack!!){
//            binding.headView.leftBut.visibility = View.GONE
//        }

        LiveEventBus.get().with("zht_all", Int::class.java).observe(this, Observer {
            badges.set(0, it)
            setUpTabBadge()
        })
        LiveEventBus.get().with("zht_wait", Int::class.java).observe(this, Observer {
            badges.set(1, it)
            setUpTabBadge()
        })
        var data = MySharedPreferences.getDmLoginData()
        if(data?.clue_mgr == 1){
            LiveEventBus.get().with("zht_dealing", Int::class.java).observe(this, Observer {
                badges.set(4, it)
                setUpTabBadge()
            })
        }
    }

    private fun initBadgeViews() {
        if (mBadgeViews == null) {
            mBadgeViews = java.util.ArrayList<TabBadgeView>()
            for (i in listFragmet.indices) {
                val tmp = TabBadgeView(this.context)
                tmp.setBadgeMargin(0, 6, 10, 0)
                tmp.setTextSize(10f)
                mBadgeViews?.add(tmp)
            }
        }
    }

    fun formatBadgeNumber(value: Int): String? {
        if (value <= 0) {
            return null
        }
        return if (value < 100) {
            Integer.toString(value)
        } else "99+"
    }

    private fun setUpTabBadge() {
        for (i in listFragmet.indices) {
            mBadgeViews?.get(i)?.setTargetView((binding.tabLayout.getChildAt(0) as ViewGroup).getChildAt(i))
            mBadgeViews?.get(i)?.setText(formatBadgeNumber(badges.get(i)))
        }
        // 需加上以下代码,不然会出现更新Tab角标后,选中的Tab字体颜色不是选中状态的颜色
        binding.tabLayout.getTabAt(binding.tabLayout.getSelectedTabPosition())?.getCustomView()?.setSelected(true)
    }

    private fun showTips(){
        binding.totleText.setVisibility(View.VISIBLE)
        binding.totleText.clearAnimation()
        val animation = AlphaAnimation(1f, 0f)
        animation.duration = 3000
        binding.totleText.startAnimation(animation)
        binding.totleText.setVisibility(View.GONE)
    }

    private fun showPop(view: View) {
        if (popupWindow == null) {
            var popbingding =
                    DataBindingUtil.inflate<DmClueTypePopItemBinding>(LayoutInflater.from(context),
                            R.layout.dm_clue_type_pop_item, null, false)
            popupWindow = PopupWindow(popbingding.root,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT)
            popbingding.clueXkt.setOnClickListener {
                changePlanType(1)
                popupWindow!!.dismiss()
            }
            popbingding.clueZht.setOnClickListener {
                changePlanType(2)
                popupWindow!!.dismiss()
            }
            popbingding.clueCzt.setOnClickListener {
                changePlanType(3)
                popupWindow!!.dismiss()
            }
        }
        popupWindow?.isOutsideTouchable = true
        context?.apply {
            popupWindow?.showAsDropDown(view, FunctionUtils.dip2px(this, -40f), -10, Gravity.BOTTOM)
        }
    }

    private fun changePlanType(type:Int){
        LiveEventBus.get().with("changePlanType").postValue(type)
    }
}
